import { TosClient } from '@volcengine/tos-sdk';
import * as fs from 'fs-extra';
import { CloudServiceInterface, FileInfo, CloudConfig } from '../types';

export class BytedanceCloudService implements CloudServiceInterface {
  private tosClient: TosClient;
  private config: CloudConfig;

  constructor(config: CloudConfig) {
    this.config = config;
    this.tosClient = new TosClient({
      accessKeyId: config.accessKeyId,
      accessKeySecret: config.secretAccessKey,
      region: config.region,
      endpoint: config.endpoint || `https://tos-${config.region}.volces.com`
    });
  }

  /**
   * 上传文件
   */
  async uploadFile(
    filePath: string,
    remotePath: string,
    onProgress?: (progress: number) => void
  ): Promise<boolean> {
    try {
      const fileContent = await fs.readFile(filePath);
      
      const result = await this.tosClient.putObject({
        bucket: this.config.bucket,
        key: remotePath,
        body: fileContent
      });
      
      if (onProgress) {
        onProgress(100);
      }
      
      return result.statusCode === 200;
    } catch (error) {
      console.error('字节云上传文件失败:', error);
      return false;
    }
  }

  /**
   * 列出文件
   */
  async listFiles(remotePath: string): Promise<FileInfo[]> {
    try {
      const files: FileInfo[] = [];
      let marker: string | undefined;
      
      do {
        const result = await this.tosClient.listObjects({
          bucket: this.config.bucket,
          prefix: remotePath,
          maxKeys: 1000,
          marker: marker
        });
        
        if (result.data.Contents) {
          result.data.Contents.forEach(item => {
            if (item.Key && item.Size !== undefined && item.LastModified && item.ETag) {
              files.push({
                key: item.Key,
                size: item.Size,
                lastModified: new Date(item.LastModified),
                etag: item.ETag.replace(/"/g, '')
              });
            }
          });
        }
        
        marker = result.data.NextMarker;
      } while (marker);
      
      return files;
    } catch (error) {
      console.error('字节云列出文件失败:', error);
      throw error;
    }
  }

  /**
   * 删除文件
   */
  async deleteFile(remotePath: string): Promise<boolean> {
    try {
      const result = await this.tosClient.deleteObject({
        bucket: this.config.bucket,
        key: remotePath
      });
      
      return result.statusCode === 204;
    } catch (error) {
      console.error('字节云删除文件失败:', error);
      return false;
    }
  }

  /**
   * 测试连接
   */
  async testConnection(): Promise<boolean> {
    try {
      const result = await this.tosClient.headBucket(this.config.bucket);
      
      return result.statusCode === 200;
    } catch (error) {
      console.error('字节云连接测试失败:', error);
      return false;
    }
  }

  /**
   * 获取文件URL
   */
  getFileUrl(remotePath: string): string {
    // 字节云TOS的公共读取URL格式
    const endpoint = this.config.endpoint || `https://tos-${this.config.region}.volces.com`;
    return `${endpoint}/${this.config.bucket}/${remotePath}`;
  }

  /**
   * 获取预签名URL
   */
  async getPresignedUrl(remotePath: string, expires: number = 3600): Promise<string> {
    try {
      // 这里需要根据字节云TOS SDK的实际API来实现预签名URL
      // 由于SDK版本可能不同，这里提供一个基础实现
      const url = this.getFileUrl(remotePath);
      return url;
    } catch (error) {
      console.error('获取预签名URL失败:', error);
      throw error;
    }
  }

  /**
   * 检查文件是否存在
   */
  async fileExists(remotePath: string): Promise<boolean> {
    try {
      const result = await this.tosClient.headObject({
        bucket: this.config.bucket,
        key: remotePath
      });
      return result.statusCode === 200;
    } catch (error) {
      return false;
    }
  }
}